package gods.bubble.parser;

import java.io.File;
import java.util.regex.Pattern;

import gods.bubble.common.StandardDocument;
import gods.bubble.util.CharsetRecognize;
import gods.bubble.util.HtmlCleaner;
import gods.bubble.util.PathURL;
import gods.bubble.util.SimpleFileIOUtil;

public class FileParser {
	public static StandardDocument parser(String url) {
		String filePath = PathURL.url2path(url);

		File file = new File(filePath);

		if (!file.exists()) {
			//System.out.println("FileParser : FileNotFound --" + url);
			return null;
		}

		StandardDocument sd = parser(file);

		return sd;
	}

	public static StandardDocument parser(File file) {
		StandardDocument sd = null;

		try {
			String[] fileName = file.getName().split("\\.");

			if (fileName.length == 1) {
				return null;
			}

			String name = fileName[0];
			String suffix = fileName[fileName.length - 1];
			String url = PathURL.path2url(file.getAbsolutePath());

			Pattern p = Pattern.compile("doc|docx|xls|xlsx");

			if (suffix.equals("htm") || suffix.equals("html")) {
				if (name.equals("index")) {
					url = url.substring(0, url.indexOf("index"));
				}

				String charset = CharsetRecognize.getCharset(file);
				String html = SimpleFileIOUtil.fileToString(file, charset);
				
				sd = HtmlParser.parseHtml(html);
				sd.raw_html = html;
				sd.content = HtmlCleaner.clean(sd.content);

			} else if (suffix.equals("pdf")) {
				sd = new StandardDocument();

				sd.title = file.getName();
				sd.content = PDFTextParser.pdftoText(file);
			} else if (p.matcher(suffix).matches()) {
				sd = new StandardDocument();

				sd.title = file.getName();
				sd.content = MSDocumentParser.parseMSDocument(file, suffix);
			} else {
				return null;
			}

			sd.fileName = name;
			sd.url = url;
		} catch (Exception e) {
			System.out.println("Failed in parsing " + file.getAbsolutePath());
			sd = null;
		}

		return sd;
	}
}
